﻿using System;
using System.Device.Location;
using System.Runtime.Serialization;
using System.Windows.Media;
using GalaSoft.MvvmLight;
using Microsoft.WindowsAzure.MobileServices;
using SkiTracker.Converter;

namespace SkiTracker.Model
{
    [DataTable(Name="Messages")]
    public class Message : ObservableObject
    {
        private DateTime _currentTime;
        public int Id { get; set; }

        public int DeviceId { get; set; }

        public string GroupName { get; set; }
        public string Text { get; set; }

        [DataMemberJsonConverter(ConverterType = typeof(GeoCoordinateJsonConverter))]
        public GeoCoordinate Coordinate { get; set; }

        public DateTime CreatedAt { get; set; }
        public DateTime CurrentServerTime
        {
            get { return _currentTime; }
            set
            {
                _currentTime = value;
                CreatedAtRelative = CalculateRelativeTime(CreatedAt);
            }
        }

        [IgnoreDataMember]
        public DateTime CreatedAtRelative { get; protected set; }

        protected virtual DateTime CalculateRelativeTime(DateTime dateTime)
        {
            var now = DateTime.UtcNow;
            var dif = now.Subtract(CurrentServerTime);
            var relative = dateTime.Add(dif);
            return relative;
        }

        public string SenderName { get; set; }

        [DataMemberJsonConverter(ConverterType = typeof(ColorJsonConverter))]
        public Color Color { get; set; }

        
        public void RaiseCreatedAtChanged()
        {
            base.RaisePropertyChanged(() => CreatedAt);
            base.RaisePropertyChanged(() => CreatedAtRelative);
            base.RaisePropertyChanged(() => SenderName);
        }
    }
}
